/**
* 版权声明：厦门睿商网络科技有限公司 版权所有 违者必究
* 日    期：2020-04-29
*/
package com.rzico.order.controller;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.rzico.annotation.Log;
import com.rzico.base.BaseController;
import com.rzico.base.CommResult;
import com.rzico.basics.entity.*;
import com.rzico.basics.service.*;
import com.rzico.core.service.SysSequenceService;
import com.rzico.entity.Filter;
import com.rzico.entity.Pageable;
import com.rzico.entity.PageResult;
import com.rzico.order.entity.*;
import com.rzico.order.enumx.AskforStatusEnum;
import com.rzico.order.enumx.OrderShippingStatusEnum;
import com.rzico.order.enumx.OrderStatusEnum;
import com.rzico.order.model.CartCouponVo;
import com.rzico.order.model.CartItemVo;
import com.rzico.order.service.*;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.Api;
import com.rzico.util.StringUtils;

import java.math.BigDecimal;
import java.util.*;

/**
 * 购物车控制层
 *
 * @author Rzico Boot
 * @version 1.0
 * @date 2020-04-29
 */
@Api(description = "购物车接口")
@RestController
@RequestMapping("/cart")
public class CartController extends BaseController {

    @Autowired
    private CartService cartService;

    @Autowired
    private CartItemService cartItemService;

    @Autowired  @Lazy
    private OrderItemService orderItemService;

    @Autowired  @Lazy
    private GroupProductService groupProductService;

    @Autowired  @Lazy
    private CouponCodeService couponCodeService;

    @Autowired  @Lazy
    private CouponService couponService;

    @Autowired  @Lazy
    private BargainProductService bargainProductService;

    @Autowired
    private MemberService memberService;

    @Autowired
    private ProductService productService;

    @Autowired
    private OrderService orderService;

    @Autowired
    protected AskforService askforService;

    @Autowired
    private EnterpriseService enterpriseService;

    @Autowired
    private ReceiverService receiverService;

    @Autowired
    private MapLineService mapLineService;

    @Autowired
    private ShopService shopService;

    @Autowired
    private ShippingService shippingService;

    @Autowired
    private SysSequenceService sysSequenceService;

    /**
     * 当前我购物车
     *
     * @return
    */
    @ApiOperation("当前我购物车")
    @GetMapping("/getCart")
    @ApiImplicitParams({@ApiImplicitParam(name = "uuid", value = "uuid", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "shopId", value = "店铺ID", dataType = "String", paramType = "query")
    })
    public CommResult<Cart> getCart(String uuid,Long shopId) {

        Member member = memberService.getCurrent();
        Cart result = cartService.getCurrent(member,uuid);
        if (result==null) {
            result = cartService.create(member,uuid);
        }

        result.setItemVoList(cartItemService.getShopItemVoList(result.getId(),shopId));

        for (CartItemVo cartItemVo:result.getItemVoList()) {
            Product product = productService.selectByPrimaryKey(cartItemVo.getProductId());
            if (product!=null) {
                if (!product.getIsMarketable() || product.getStock()<=0) {
                    cartItemVo.setChk(false);
                }
                cartItemVo.setPrice(product.getMemberPrice(member));

                CartItem cartItem = new CartItem();
                cartItem.setId(cartItemVo.getId());
                cartItem.setChk(cartItemVo.getChk());
                cartItem.setPrice(product.getMemberPrice(member));
                cartItemService.updateByPrimaryKeySelective(cartItem);
            }
        }

        Map<String,Object> data = new HashMap<>();
        data.put("cart",result);
        return CommResult.success(data);

    }

    /**
     * 当前我购物车数量金额
     *
     * @return
     */
    @ApiOperation("当前我购物车数量金额")
    @GetMapping("/count")
    @ApiImplicitParams({@ApiImplicitParam(name = "uuid", value = "uuid", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "shopId", value = "店铺ID", dataType = "String", paramType = "query")
    })
    public CommResult<Cart> count(String uuid,Long shopId) {

        Member member = memberService.getCurrent();
        Cart result = cartService.getCurrent(member,uuid);
        Map<String,Object> data = new HashMap<>();
        if (result==null) {
            data.put("amount",0);
            data.put("quantity",0);
        } else {
            result.setItemList(cartItemService.getShopItemList(result.getId(),shopId));
            data.put("amount",result.getAmount());
            data.put("quantity",result.getQuantity());
        }
        return CommResult.success(data);

    }

    /**
     * 加入购物车
     **/
    @ApiOperation("加入购物车")
    @PostMapping("/add")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "productId", value = "商品", dataType = "Long", paramType = "query") ,
            @ApiImplicitParam(name = "shopId", value = "店铺ID", dataType = "Long", paramType = "query") ,
            @ApiImplicitParam(name = "quantity", value = "数量", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "promotionId", value = "活动", dataType = "Long", paramType = "query")
    })
    public CommResult<Cart> add(String uuid,Long productId,Integer quantity,Long promotionId,Long shopId) {

        Member member = memberService.getCurrent();
        Cart cart = cartService.getCurrent(member,uuid);
        if (cart==null) {
            cart = cartService.create(member,uuid);
        }
        cart.setItemList(cartItemService.getItemList(cart.getId()));

        CartItem cartItem = cart.findItem(productId);
        Boolean isNew = false;
        if (cartItem==null) {
            cartItem = new CartItem();
            cartItem.setCartId(cart.getId());
            cartItem.setPrice(BigDecimal.ZERO);
            cartItem.setQuantity(0);
            isNew = true;
        }

        Product product = productService.selectByPrimaryKey(productId);
        if (product==null) {
            return CommResult.error("商品ID无效");
        }
        if (!product.getIsMarketable()) {
            return CommResult.error("商品已下架");
        }

        cartItem.setProductId(productId);
        cartItem.setPrice(product.getMemberPrice(member));
        cartItem.setQuantity(cartItem.getQuantity()+quantity);
        if (product.getMaxLimit()!=null && product.getMaxLimit()>0) {
            if (cartItem.getQuantity()>product.getMaxLimit()) {
                return CommResult.error("大于限额量");
            }
        }
        cartItem.setPromotionId(promotionId);
        cartItem.setChk(true);
        if (isNew) {
            cartItemService.insertUseGeneratedKeys(cartItem);
        } else {
            cartItemService.updateByPrimaryKeySelective(cartItem);
        }
        return CommResult.success(cartItemService.getCartShopItemVo(cartItem.getId(),shopId));

    }

    /**
     * 修改数量及选中
     **/
    @ApiOperation("修改数量及选中")
    @PostMapping("/update")
    @ApiImplicitParams({
    })
    public CommResult<Cart> update(@RequestBody List<CartItem> cartItems) {
        for (CartItem cartItem:cartItems) {
            CartItem chk = new CartItem();
            if (cartItem.getChk()==null) {
                chk.setChk(true);
            } else {
                chk.setChk(cartItem.getChk());
            }
            chk.setId(cartItem.getId());
            chk.setQuantity(cartItem.getQuantity());
            cartItemService.updateByPrimaryKeySelective(chk);
        }
        return CommResult.success();
    }

    /**
     * 立即购买
     **/
    @ApiOperation("立即购买")
    @PostMapping("/buyNow")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "productId", value = "商品", dataType = "Long", paramType = "query") ,
            @ApiImplicitParam(name = "quantity", value = "数量", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "promotionId", value = "活动", dataType = "Long", paramType = "query")
    })
    public CommResult<Cart> buyNow(String uuid,Long productId,Integer quantity,Long promotionId) {

        Member member = memberService.getCurrent();
        Cart cart = cartService.getCurrent(member,uuid);
        if (cart==null) {
            cart = cartService.create(member,uuid);
        }
        cart.setItemList(cartItemService.getItemList(cart.getId()));
        for (CartItem cartItem:cart.getItemList()) {
            cartItem.setChk(false);
            cartItemService.updateByPrimaryKeySelective(cartItem);
        }

        Boolean isNew = false;
        CartItem cartItem = cart.findItem(productId);
        if (cartItem==null) {
            cartItem = new CartItem();
            cartItem.setCartId(cart.getId());
            cartItem.setPrice(BigDecimal.ZERO);
            cartItem.setQuantity(0);
            isNew = true;
        }
        Product product = productService.selectByPrimaryKey(productId);
        if (product==null) {
            return CommResult.error("商品ID无效");
        }
        if (!product.getIsMarketable()) {
            return CommResult.error("商品已下架");
        }
        cartItem.setProductId(productId);
        cartItem.setChk(true);
        cartItem.setPrice(product.getMemberPrice(member));
        cartItem.setQuantity(quantity);
        cartItem.setPromotionId(promotionId);
        if (isNew) {
            cartItemService.insertUseGeneratedKeys(cartItem);
        } else {
            cartItemService.updateByPrimaryKeySelective(cartItem);
        }
        return CommResult.success();

    }


    /**
     * 立即购买团购商品
     **/
    @ApiOperation("立即购买团购商品")
    @PostMapping("/buyNowForGroupBuy")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "groupBuyId", value = "订单号", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "uuid", value = "uuid", dataType = "Long", paramType = "query")
    })
    public CommResult<Cart> buyNowForGroupBuy(String uuid,Long groupBuyId) {

        Member member = memberService.getCurrent();
        Cart cart = cartService.getCurrent(member,uuid);
        if (cart==null) {
            cart = cartService.create(member,uuid);
        }
        cart.setItemList(cartItemService.getItemList(cart.getId()));
        for (CartItem cartItem:cart.getItemList()) {
            cartItem.setChk(false);
            cartItemService.updateByPrimaryKeySelective(cartItem);
        }

        List<GroupProduct> itemList = groupProductService.getItemList(groupBuyId);

        for (GroupProduct groupProduct:itemList) {

            Boolean isNew = false;
            CartItem cartItem = cart.findItem(groupProduct.getProductId());
            if (cartItem == null) {
                cartItem = new CartItem();
                cartItem.setCartId(cart.getId());
                cartItem.setPrice(BigDecimal.ZERO);
                cartItem.setQuantity(0);
                isNew = true;

            }

            Product product = productService.selectByPrimaryKey(groupProduct.getProductId());
            if (product == null) {
                return CommResult.error("商品ID无效");
            }
            if (!product.getIsMarketable()) {
                return CommResult.error("商品已下架");
            }

            cartItem.setProductId(groupProduct.getProductId());
            cartItem.setChk(true);
            cartItem.setPrice(product.getPrice());
            cartItem.setQuantity(groupProduct.getQuantity().setScale(0,BigDecimal.ROUND_HALF_DOWN).intValue());
            cartItem.setPromotionId(null);
            if (isNew) {
                cartItemService.insertUseGeneratedKeys(cartItem);
            } else {
                cartItemService.updateByPrimaryKeySelective(cartItem);
            }

        }
        return CommResult.success();

    }


    /**
     * 立即购买兑换券购买
     **/
    @ApiOperation("立即购买兑换券购买")
    @PostMapping("/buyNowForCoupon")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "uuid", value = "uuid", dataType = "Long", paramType = "query")
    })
    public CommResult<Cart> buyNowForCoupon(@RequestBody List<CartCouponVo> cartCouponVo,String uuid) {

        Member member = memberService.getCurrent();
        Cart cart = cartService.getCurrent(member,uuid);
        if (cart==null) {
            cart = cartService.create(member,uuid);
        }
        cart.setItemList(cartItemService.getItemList(cart.getId()));
        for (CartItem cartItem:cart.getItemList()) {
            cartItem.setChk(false);
            cartItemService.updateByPrimaryKeySelective(cartItem);
        }

        for (CartCouponVo couponCodeVo:cartCouponVo) {

            CouponCode couponCode = couponCodeService.selectByPrimaryKey(couponCodeVo.getId());
            Coupon coupon = couponService.selectByPrimaryKey(couponCode.getCouponId());
            Product product = productService.selectByPrimaryKey(coupon.getProductId());
            if (product == null) {
                return CommResult.error("商品ID无效");
            }
            if (!product.getIsMarketable()) {
                return CommResult.error("商品已下架");
            }


            Boolean isNew = false;
            CartItem cartItem = cart.findItem(product.getId());
            if (cartItem == null) {
                cartItem = new CartItem();
                cartItem.setCartId(cart.getId());
                cartItem.setPrice(BigDecimal.ZERO);
                cartItem.setQuantity(0);
                isNew = true;

            }

            cartItem.setProductId(product.getId());
            cartItem.setChk(true);
            cartItem.setPrice(product.getPrice());
            cartItem.setQuantity(coupon.getQuantity().intValue()*couponCodeVo.getQuantity());
            cartItem.setPromotionId(null);
            if (isNew) {
                cartItemService.insertUseGeneratedKeys(cartItem);
            } else {
                cartItemService.updateByPrimaryKeySelective(cartItem);
            }

        }
        return CommResult.success();

    }

    /**
     * 立即购买砍价商品
     **/
    @ApiOperation("立即购买砍价商品")
    @PostMapping("/buyNowForBargainBuy")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "bargainBuyId", value = "砍价ID", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "uuid", value = "uuid", dataType = "Long", paramType = "query")
    })
    public CommResult<Cart> buyNowForBarginBuy(String uuid,Long bargainBuyId) {

        Member member = memberService.getCurrent();
        Cart cart = cartService.getCurrent(member,uuid);
        if (cart==null) {
            cart = cartService.create(member,uuid);
        }
        cart.setItemList(cartItemService.getItemList(cart.getId()));
        for (CartItem cartItem:cart.getItemList()) {
            cartItem.setChk(false);
            cartItemService.updateByPrimaryKeySelective(cartItem);
        }

        List<BargainProduct> itemList = bargainProductService.getItemList(bargainBuyId);

        for (BargainProduct groupProduct:itemList) {

            Boolean isNew = false;
            CartItem cartItem = cart.findItem(groupProduct.getProductId());
            if (cartItem == null) {
                cartItem = new CartItem();
                cartItem.setCartId(cart.getId());
                cartItem.setPrice(BigDecimal.ZERO);
                cartItem.setQuantity(0);
                isNew = true;

            }

            Product product = productService.selectByPrimaryKey(groupProduct.getProductId());
            if (product == null) {
                return CommResult.error("商品ID无效");
            }
            if (!product.getIsMarketable()) {
                return CommResult.error("商品已下架");
            }

            cartItem.setProductId(groupProduct.getProductId());
            cartItem.setChk(true);
            cartItem.setPrice(product.getPrice());
            cartItem.setQuantity(groupProduct.getQuantity().setScale(0,BigDecimal.ROUND_HALF_DOWN).intValue());
            cartItem.setPromotionId(null);
            if (isNew) {
                cartItemService.insertUseGeneratedKeys(cartItem);
            } else {
                cartItemService.updateByPrimaryKeySelective(cartItem);
            }

        }
        return CommResult.success();

    }

    /**
     * 再来一单
     **/
    @ApiOperation("再来一单")
    @PostMapping("/buyForOrder")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderId", value = "订单号", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "uuid", value = "uuid", dataType = "Long", paramType = "query")
    })
    public CommResult<Cart> buyForOrder(String uuid,Long orderId) {

        Member member = memberService.getCurrent();
        Cart cart = cartService.getCurrent(member,uuid);
        if (cart==null) {
            cart = cartService.create(member,uuid);
        }
        cart.setItemList(cartItemService.getItemList(cart.getId()));
        for (CartItem cartItem:cart.getItemList()) {
            cartItem.setChk(false);
            cartItemService.updateByPrimaryKeySelective(cartItem);
        }

        List<OrderItem> itemList = orderItemService.getItemList(orderId);

        for (OrderItem orderItem:itemList) {
            if (orderItem.getIsGift()==true) {
                break;
            }
            Boolean isNew = false;
            CartItem cartItem = cart.findItem(orderItem.getProductId());
            if (cartItem == null) {
                cartItem = new CartItem();
                cartItem.setCartId(cart.getId());
                cartItem.setPrice(BigDecimal.ZERO);
                cartItem.setQuantity(0);
                isNew = true;

            }
            Product product = productService.selectByPrimaryKey(orderItem.getProductId());
            if (product == null) {
                return CommResult.error("商品ID无效");
            }
            if (!product.getIsMarketable()) {
                return CommResult.error("商品已下架");
            }
            cartItem.setProductId(orderItem.getProductId());
            cartItem.setChk(true);
            cartItem.setPrice(product.getMemberPrice(member));
            cartItem.setQuantity(orderItem.getQuantity().setScale(0,BigDecimal.ROUND_HALF_DOWN).intValue());
            cartItem.setPromotionId(null);
            if (isNew) {
                cartItemService.insertUseGeneratedKeys(cartItem);
            } else {
                cartItemService.updateByPrimaryKeySelective(cartItem);
            }
        }
        return CommResult.success();

    }

    /**
     * 批量删除购物车商品
     *
     * @param ids
     * @return
     */
    @Log(desc = "批量删除购物车商品", type = Log.LOG_TYPE.DEL)
    @ApiOperation("批量删除购物车商品,ids用逗号拼接")
    @PostMapping("/del/{ids}")
    public CommResult<Cart> del(@PathVariable String ids) {

        int affectCount =  cartItemService.deleteByIds(ids.split(","));
        if (affectCount <= 0){
            return CommResult.error();
        }
        return CommResult.success();

    }

    /**
     * 测试订单回调
     *
     * @param id
     * @return
     */

    @GetMapping("/orderTest/{id}")
    public void orderTest(Long id) {

        Map<String,Object> params = new HashMap<>();
        params.put("orderStatus",1);
        params.put("shippingStatus", OrderShippingStatusEnum.SHIPPING_STATUS_SHIPPNG.getId());
        params.put("estimateBeforeDate", DateUtils.addDays(new Date(),-7));
        List<Order> orderList = orderService.selectList(params);

        for (Order order:orderList) {
            try {
                //检查存在未完成退款申请，不签收

                Map<String,Object> chkParams = new HashMap<>();
                chkParams.put("orderId",order.getId());

                List<Askfor> askforList = askforService.selectList(chkParams);
                for (Askfor rn:askforList) {
                    if (!rn.getStatus().equals(AskforStatusEnum.ASKFOR_STATUS_COMPLETE.getId())
                            &&
                            !rn.getStatus().equals(AskforStatusEnum.ASKFOR_STATUS_CANCLEED.getId())
                            ) {
                        continue;
                    }
                }

                orderService.received(order.getId(),true);

            } catch (Exception e) {
                logger.error(e.getMessage());
            }
        }

//        Order order = orderService.selectByPrimaryKey(id);
//        if (order==null) {
//            return;
//        }
//        if (order.getOrderStatus().equals(OrderStatusEnum.ORDER_STATUS_CONFIRM.getId()) && order.getShippingStatus().equals(OrderShippingStatusEnum.SHIPPING_STATUS_UNSHIPPNG.getId())) {
//            Enterprise enterprise = enterpriseService.selectByPrimaryKey(order.getEnterpriseId());
//            Shop shop = null;
//            String shippingEmployeeId = null;
//            if (order.getReceiverId() != null) {
//                Double lat = order.getLat();
//                Double lng = order.getLng();
//                Receiver receiver = receiverService.selectByPrimaryKey(order.getReceiverId());
//                if (receiver != null) {
//                    MapLine mapLine = mapLineService.findByPoint(enterprise,null, receiver.getLat(), receiver.getLng());
//                    if (mapLine != null) {
//                        shop = shopService.selectByPrimaryKey(mapLine.getShopId());
//                        shippingEmployeeId = mapLine.getShippingEmployeeId();
//                    }
//                    lat = receiver.getLat();
//                    lng = receiver.getLng();
//                }
//                if (shop == null) {
//                    shop = shopService.findByPoint(enterprise,lat , lng );
//                }
//            }
//            if (shop==null && order.getShopId()!=null) {
//                shop = shopService.selectByPrimaryKey(order.getShopId());
//            }
//
//            if (shop != null) {
//
//                List<OrderItem> itemList = new ArrayList<>();
//                List<OrderItem> orderItemList = orderItemService.getItemList(order.getId());
//                for (OrderItem orderItem : orderItemList) {
//                    orderItem.setShippedQuantity(orderItem.getQuantity().subtract(orderItem.getShippedQuantity()));
//                    itemList.add(orderItem);
//                }
//
//                Warehouse warehouse = orderService.shipping(order.getId(), shop.getId(), order.getOrderDate(), order.getWeekTime(), itemList, sysSequenceService.generate("warehouse"));
//
//                //人工报单时，自动发货
//
//                if (shippingEmployeeId != null) {
//                    Shipping shipping = new Shipping();
//                    shipping.setWarehouseId(warehouse.getId());
//                    shipping.setEnterpriseId(warehouse.getEnterpriseId());
//                    List<Shipping> shippingList = shippingService.select(shipping);
//                    for (Shipping shipping1 : shippingList) {
//                        shippingService.dispatch(shipping1.getId(), shop.getId(), shippingEmployeeId);
//                    }
//                }
//            }
//        }
        //String code = memberService.getMaxCode("10216");
        //orderService.received(3071L,false);
       // System.out.println(code);
    }


}
